package com.mrbeard.greenbroswer.services;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;

import com.google.gson.Gson;
import com.mrbeard.greenbroswer.entites.Device;
import com.mrbeard.greenbroswer.entites.Strategy;
import com.mrbeard.greenbroswer.entites.UrlList;
import com.mrbeard.greenbroswer.utils.DeviceUtil;
import com.mrbeard.greenbroswer.utils.FileUtil;
import com.mrbeard.greenbroswer.utils.FormatUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

import java.util.ArrayList;
import java.util.List;

public class GetMessageService extends Service{
    private String strategyMessage;
    private String urlListMessage;

    public GetMessageService() {
    }



    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        //throw new UnsupportedOperationException("Not yet implemented");
        return null;
    }

    @Override
    public void onCreate() {

        //接收时间策略
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    getStrategy();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        //接受UrlList
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    getUrlList();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @Override
    public void onDestroy() {

    }

    @Override
    public void onStart(Intent intent, int startid) {
        //接收时间策略
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    getStrategy();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        //接受UrlList
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    getUrlList();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 接受时间策略
     */
    public void getStrategy() throws Exception {
        while(true){
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("118.89.52.198");
            factory.setRequestedHeartbeat(2);//是否断网
            // 获取到连接以及mq通道
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();
            // 声明队列
            channel.queueDeclare("topic.queue1", true, false, false, null);
            //获取deviceId
            DeviceUtil deviceUtil = new DeviceUtil(this);
            Device device = deviceUtil.getDevice();
            // 绑定队列到交换机
            channel.queueBind("topic.queue1", "topicExchage", device.getImei());
            // 同一时刻服务器只会发一条消息给消费者
            channel.basicQos(1);
            // 定义队列的消费者
            QueueingConsumer consumer = new QueueingConsumer(channel);
            // 监听队列，手动返回完成
            channel.basicConsume("topic.queue1", false, consumer);
            // 获取消息
            while (true) {
                QueueingConsumer.Delivery delivery = consumer.nextDelivery();
                strategyMessage = new String(delivery.getBody());
                Thread.sleep(10);
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                if (strategyMessage != null) {
                    break;
                }
            }

            //如果接收到信息则存入文件中
            if (strategyMessage != null) {
                //System.out.print(strategyMessage);
                List<Strategy> listStrategy = new ArrayList<Strategy>();
                Gson gson = new Gson();
                //android.util.Log.e("url","gson.toJson(strategyMessage)="+gson.toJson(strategyMessage));
                listStrategy = FormatUtil.formatStrategyFromJson(strategyMessage);
                StringBuilder stringBuilder = new StringBuilder();
                for (Strategy strategy : listStrategy) {
                    stringBuilder.append(FormatUtil.formatTimeStrategyToString(strategy));
                }
                String content = stringBuilder.toString();
                creatFile(".timeStrategy.dat", content);
                //将strategyMessage重置空，以备下次接收
                strategyMessage = null;
            }
        }


    }


    /**
     * 接受urlList
     */
    public void getUrlList() throws Exception {

        while(true){
            ConnectionFactory factory = new ConnectionFactory();
            factory.setHost("118.89.52.198");
            factory.setRequestedHeartbeat(2);//是否断网
            // 获取到连接以及mq通道
            Connection connection = factory.newConnection();
            Channel channel = connection.createChannel();
            // 声明队列
            channel.queueDeclare("topic.queue2", true, false, false, null);
            //获取deviceId
            DeviceUtil deviceUtil = new DeviceUtil(this);
            Device device = deviceUtil.getDevice();
            // 绑定队列到交换机
            channel.queueBind("topic.queue2", "topicExchage", device.getImei());
            // 同一时刻服务器只会发一条消息给消费者
            channel.basicQos(1);
            // 定义队列的消费者
            QueueingConsumer consumer = new QueueingConsumer(channel);
            // 监听队列，手动返回完成
            channel.basicConsume("topic.queue2", false, consumer);
            // 获取消息
            while (true) {
                QueueingConsumer.Delivery delivery = consumer.nextDelivery();
                urlListMessage = new String(delivery.getBody());
                Thread.sleep(10);
                channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                if (urlListMessage != null) {
                    break;
                }
            }

            //如果接收到信息则存入文件中
            if (urlListMessage != null) {
                Gson gson = new Gson();
                List<UrlList> lis3 = new ArrayList<UrlList>();
                lis3 = FormatUtil.formatUrlListFromJson(urlListMessage);

                StringBuilder stu = new StringBuilder();
                for (UrlList u : lis3) {
                    stu.append(FormatUtil.formatUrlListToString(u));
                }

                String content = stu.toString();

                creatFile(".urllist.dat", content);

                //将urlListMessage重置空，以备下次接收
                urlListMessage = null;
            }
        }


    }

    /**
     * 创建文件
     */
    public void creatFile(String fileName, String fileContent) {

        try {
            FileUtil fileUtil = new FileUtil();

            String state = fileUtil.setFileContent(fileName, fileContent);
            if (state.equals("file is exists")) {
                //Toast.makeText(this,"file is exists",Toast.LENGTH_SHORT).show();
            } else {
                //Toast.makeText(this,"get Message success",Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
